< previous page page_465 next page >

Page 465
window has been programmed to intercept specific events, such as the MouseMove event. The Visual Basic form "knows" to run the MouseMove event procedure because that is what it has been programmed to do. But what about all the Windows messages that the form is ignoring? And what if you want to change the way Windows handles the existing messages?
To intercept and react to messages, you must change the way the form class handles events. You do so through a technique known as subclassing, which, prior to VB version 5.0, could only be accomplished with a custom control. However, now that callbacks are possible, you can use a callback function with the SetWindowLong API function to intercept Windows messages.
Creating an Event Handler with Subclassing
A good example of subclassing is in the article "Passing Function Pointers to DLL Procedures and Type Libraries," which is included in the Visual Basic help files. The code for that example is shown in Listings 20.9 and 20.10, followed by a step-by-step explanation.
Listing 20.9 SUBCLASS.ZIPSubclassing Example
Declare Function CallWindowProc Lib "user32" Alias "CallWindowProcA" _
                 (ByVal lpPrevWndFunc As Long, ByVal hwnd As Long, ByVal Msg _
                 As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd _
                 As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long

Global Const GWL_WNDPROC = -4
Public lpPrevWndProc As Long
Public gHW As Long

Function WindowProc(ByVal hw As Long, ByVal uMsg As Long, ByVal wParam As Long, _
         ByVal lParam As Long) As Long
    Debug.Print "Message: "; hw, uMsg, wParam, lParam
    WindowProc = CallWindowProc(lpPrevWndProc, hw, uMsg, wParam, lParam)
End Function

Public Sub Hook()
    lpPrevWndProc = SetWindowLong(gHW, GWL_WNDPROC, _
    AddressOf WindowProc)
End Sub

Public Sub Unhook()
    Dim temp As Long
    temp = SetWindowLong(gHW, GWL_WNDPROC, _
    lpPrevWndProc)
End Sub
Although the code in Listing 20.9 is used to intercept messages sent to a form, a rule for callbacks is that they must be located in a module, so that is the place where the guts of the sample code resides. The form-level code is shown in Listing 20.10.

 
< previous page page_465 next page >